package com.selly.hanjuang;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import com.selly.hanjuang.NewOrderActivity.CreateNewPemesanan;
import com.selly.hanjuang.lib.JSONParser;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore.Images.Media;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MenuUpload extends Activity {
	
	//final Context context = this;

	//private String url_uploaded_image = "http://10.0.2.2/hanjuang/json/create_uploaded_image.php";
	private String url_uploaded_image = "http://hanjuang.web.id/json/create_uploaded_image.php";
	JSONParser jsonParser = new JSONParser();

	SharedPreferences mGameSettings;
	public static final String DEBUG_TAG = "Hanjuang Log";
	public static final String GAME_PREFERENCES = "GamePrefs";
	public static final String GAME_PREFERENCES_AVATAR = "Avatar"; // String URL
																	// to image
	static final int TAKE_AVATAR_CAMERA_REQUEST = 1;
	static final int TAKE_AVATAR_GALLERY_REQUEST = 2;

	// JSON Node names
	private static final String TAG_SUCCESS = "success";

	EditText txtIDPemesanan;
	TextView messageText;
	Button uploadButton;
	int serverResponseCode = 0;
	ProgressDialog dialog = null;

	String upLoadServerUri = null;
	String sIDPemesanan = "";

	/********** File Path *************/
	String uploadFilePath = "";
	String sNama_file = "";

	// String uploadFileName = "user login.png";

	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_upload_to_server);

		// Retrieve the shared preferences
		mGameSettings = getSharedPreferences(GAME_PREFERENCES,
				Context.MODE_PRIVATE);

		// Initialize the avatar button
		initAvatar();

		txtIDPemesanan = (EditText) findViewById(R.id.txtIDPemesanan);

		uploadButton = (Button) findViewById(R.id.uploadButton);
		messageText = (TextView) findViewById(R.id.messageText);

		// messageText.setText("Uploading file path :- '/mnt/sdcard/"+uploadFileName+"'");
		messageText.setText(" " + uploadFilePath + "");

		/************* Php script path ****************/
		// upLoadServerUri =
		// "http://www.androidexample.com/media/UploadToServer.php";
		// upLoadServerUri = "http://10.0.2.2/uploadtoserva/UploadToServer.php";
		// upLoadServerUri = getString(R.string.web_name) +
		// "/UploadToServer.php";
		// upLoadServerUri = "http://hanjuang.web.id/UploadToServer.php";
		//upLoadServerUri = "http://10.0.2.2/hanjuang/UploadToServer.php";
		upLoadServerUri = "http://hanjuang.web.id/UploadToServer.php";

		uploadButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {

				dialog = ProgressDialog.show(MenuUpload.this, "",
						"Uploading file...", true);

				new Thread(new Runnable() {
					public void run() {
						runOnUiThread(new Runnable() {
							public void run() {
								messageText.setText("uploading started.....");
							}
						});

						// uploadFile(uploadFilePath + "" + uploadFileName);
						// upLoadServerUri

						// sIDPemesanan = txtIDPemesanan.getText().toString();
						// if (sIDPemesanan.length() > 0) {
						uploadFile(uploadFilePath);
						// }
					}
				}).start();
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		switch (requestCode) {
		case TAKE_AVATAR_CAMERA_REQUEST:

			if (resultCode == Activity.RESULT_CANCELED) {
				// Avatar camera mode was canceled.
			} else if (resultCode == Activity.RESULT_OK) {

				// Took a picture, use the downsized camera image provided by
				// default
				Bitmap cameraPic = (Bitmap) data.getExtras().get("data");
				if (cameraPic != null) {
					try {
						saveAvatar(cameraPic);
					} catch (Exception e) {
						Log.e(DEBUG_TAG,
								"saveAvatar() with camera image failed.", e);
					}
				}
			}
			break;
		case TAKE_AVATAR_GALLERY_REQUEST:

			if (resultCode == Activity.RESULT_CANCELED) {
				// Avatar gallery request mode was canceled.
			} else if (resultCode == Activity.RESULT_OK) {

				// Get image picked
				Uri photoUri = data.getData();
				// uploadFilePath = photoUri.toString();
				if (photoUri != null) {
					try {
						int maxLength = 600;
						// Full size image likely will be large. Let's scale the
						// graphic to a more appropriate size for an avatar
						Bitmap galleryPic = Media.getBitmap(
								getContentResolver(), photoUri);
						Bitmap scaledGalleryPic = createScaledBitmapKeepingAspectRatio(
								galleryPic, maxLength);
						saveAvatar(scaledGalleryPic);
					} catch (Exception e) {
						Log.e(DEBUG_TAG,
								"saveAvatar() with gallery picker failed.", e);
					}
				}
			}
			break;
		}
	}

	/**
	 * Scale a Bitmap, keeping its aspect ratio
	 * 
	 * @param bitmap
	 *            Bitmap to scale
	 * @param maxSide
	 *            Maximum length of either side
	 * @return a new, scaled Bitmap
	 */
	private Bitmap createScaledBitmapKeepingAspectRatio(Bitmap bitmap,
			int maxSide) {
		int orgHeight = bitmap.getHeight();
		int orgWidth = bitmap.getWidth();

		// scale to no longer any either side than 75px
		// int scaledWidth = (orgWidth >= orgHeight) ? maxSide : (int) ((float)
		// maxSide * ((float) orgWidth / (float) orgHeight));
		// int scaledHeight = (orgHeight >= orgWidth) ? maxSide : (int) ((float)
		// maxSide * ((float) orgHeight / (float) orgWidth));

		// create the scaled bitmap
		// Bitmap scaledGalleryPic = Bitmap.createScaledBitmap(bitmap,
		// scaledWidth, scaledHeight, true);
		Bitmap scaledGalleryPic = Bitmap.createScaledBitmap(bitmap, orgWidth,
				orgHeight, true);
		return scaledGalleryPic;
	}

	/**
	 * Initialize the Avatar
	 */
	private void initAvatar() {
		// Handle password setting dialog
		ImageButton avatarButton = (ImageButton) findViewById(R.id.ImageButton_Avatar);

		/*
		 * if (mGameSettings.contains(GAME_PREFERENCES_AVATAR)) { String
		 * strAvatarUri = mGameSettings.getString( GAME_PREFERENCES_AVATAR,
		 * "android.resource://yo.myuu.uploadtoserva/drawable/avatar"); Uri
		 * imageUri = Uri.parse(strAvatarUri);
		 * avatarButton.setImageURI(imageUri); } else {
		 * avatarButton.setImageResource(R.drawable.avatar); }
		 */
		avatarButton.setImageResource(R.drawable.avatar);

		avatarButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				sIDPemesanan = txtIDPemesanan.getText().toString();
				// Toast.makeText(getApplicationContext(), "sIDPemesanan : " +
				// sIDPemesanan, Toast.LENGTH_LONG) .show();
				if (sIDPemesanan.length() > 0) {
					String strAvatarPrompt = "Take your picture to store as your avatar!";
					Intent pictureIntent = new Intent(
							android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
					startActivityForResult(Intent.createChooser(pictureIntent,
							strAvatarPrompt), TAKE_AVATAR_CAMERA_REQUEST);
				} else {
					messageText.setText("Masukkan ID Pemesanan!!");
				}
			}
		});

		avatarButton.setOnLongClickListener(new View.OnLongClickListener() {
			public boolean onLongClick(View v) {
				sIDPemesanan = txtIDPemesanan.getText().toString();
				// Toast.makeText(getApplicationContext(), "sIDPemesanan : " +
				// sIDPemesanan, Toast.LENGTH_LONG).show();
				if (sIDPemesanan.length() > 0) {
					String strAvatarPrompt = "Choose a picture to use as your avatar!";
					Intent pickPhoto = new Intent(Intent.ACTION_PICK);
					pickPhoto.setType("image/*");
					startActivityForResult(
							Intent.createChooser(pickPhoto, strAvatarPrompt),
							TAKE_AVATAR_GALLERY_REQUEST);
				} else {
					messageText.setText("Masukkan ID Pemesanan!!");
				}
				return true;

			}
		});
	}

	private void saveAvatar(Bitmap avatar) {
		sIDPemesanan = txtIDPemesanan.getText().toString();
		String strAvatarFilename = "bukti" + sIDPemesanan + ".jpg";
		sNama_file = strAvatarFilename;
		try {
			avatar.compress(CompressFormat.JPEG, 100,
					openFileOutput(strAvatarFilename, MODE_PRIVATE));
		} catch (Exception e) {
			Log.e(DEBUG_TAG, "Avatar compression and save failed.", e);
		}

		Uri imageUriToSaveCameraImageTo = Uri.fromFile(new File(MenuUpload.this
				.getFilesDir(), strAvatarFilename));

		Editor editor = mGameSettings.edit();
		editor.putString(GAME_PREFERENCES_AVATAR,
				imageUriToSaveCameraImageTo.getPath());
		editor.commit();

		// Update the settings screen
		ImageButton avatarButton = (ImageButton) findViewById(R.id.ImageButton_Avatar);
		String strAvatarUri = mGameSettings.getString(GAME_PREFERENCES_AVATAR,
				"android.resource://com.selly.hanjuang/drawable/avatar");

		uploadFilePath = strAvatarUri;

		Uri imageUri = Uri.parse(strAvatarUri);
		avatarButton.setImageURI(null); // Workaround for refreshing an
										// ImageButton, which tries to cache the
										// previous image Uri. Passing null
										// effectively resets it.
		avatarButton.setImageURI(imageUri);
	}

	public int uploadFile(String sourceFileUri) {

		/*
		 * if (sIDPemesanan.length() < 1) { /*
		 * Toast.makeText(getApplicationContext(), "Masukkan ID Pemesanan!!",
		 * Toast.LENGTH_LONG) .show(); return 0; } else {
		 */

		String fileName = sourceFileUri;

		HttpURLConnection conn = null;
		DataOutputStream dos = null;
		String lineEnd = "\r\n";
		String twoHyphens = "--";
		String boundary = "*****";
		int bytesRead, bytesAvailable, bufferSize;
		byte[] buffer;
		int maxBufferSize = 1 * 1024 * 1024;
		File sourceFile = new File(sourceFileUri);

		if (!sourceFile.isFile()) {

			dialog.dismiss();
			/*
			 * Log.e("uploadFile", "Source File not exist :" +uploadFilePath +
			 * "" + uploadFileName);
			 */
			Log.e("uploadFile", "Source File not exist :" + uploadFilePath);

			runOnUiThread(new Runnable() {
				public void run() {
					/*
					 * messageText.setText("Source File not exist :"
					 * +uploadFilePath + "" + uploadFileName);
					 */

					messageText.setText("Source File not exist :"
							+ uploadFilePath);
				}
			});

			return 0;

		} else {
			try {

				// open a URL connection to the Servlet
				FileInputStream fileInputStream = new FileInputStream(
						sourceFile);
				URL url = new URL(upLoadServerUri);

				// Open a HTTP connection to the URL
				conn = (HttpURLConnection) url.openConnection();
				conn.setDoInput(true); // Allow Inputs
				conn.setDoOutput(true); // Allow Outputs
				conn.setUseCaches(false); // Don't use a Cached Copy
				conn.setRequestMethod("POST");
				conn.setRequestProperty("Connection", "Keep-Alive");
				conn.setRequestProperty("ENCTYPE", "multipart/form-data");
				conn.setRequestProperty("Content-Type",
						"multipart/form-data;boundary=" + boundary);
				conn.setRequestProperty("uploaded_file", fileName);

				dos = new DataOutputStream(conn.getOutputStream());

				dos.writeBytes(twoHyphens + boundary + lineEnd);
				// dos.writeBytes("Content-Disposition: form-data; name='uploaded_file';filename='"
				// + fileName + "'" + lineEnd);
				dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
						+ fileName + "\"" + lineEnd);
				dos.writeBytes(lineEnd);

				// create a buffer of maximum size
				bytesAvailable = fileInputStream.available();

				bufferSize = Math.min(bytesAvailable, maxBufferSize);
				buffer = new byte[bufferSize];

				// read file and write it into form...
				bytesRead = fileInputStream.read(buffer, 0, bufferSize);

				while (bytesRead > 0) {

					dos.write(buffer, 0, bufferSize);
					bytesAvailable = fileInputStream.available();
					bufferSize = Math.min(bytesAvailable, maxBufferSize);
					bytesRead = fileInputStream.read(buffer, 0, bufferSize);

				}

				// send multipart form data necesssary after file data...
				dos.writeBytes(lineEnd);
				dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

				// Responses from the server (code and message)
				serverResponseCode = conn.getResponseCode();
				String serverResponseMessage = conn.getResponseMessage();

				Log.i("uploadFile", "HTTP Response is : "
						+ serverResponseMessage + ": " + serverResponseCode);

				if (serverResponseCode == 200) {

					runOnUiThread(new Runnable() {
						public void run() {

							// String msg =
							// "File Upload Completed.\n\n See uploaded file here : \n\n"
							// + "";
							String msg = "File Upload Completed.";

							//messageText.setText(msg);
							messageText.setText("BUKTI PENDAFTARAN TELAH KAMI TERIMA. " +
									"BARANG AKAN DIKIRIM MAKSIMAL SEMINGGU SETELAH PEMBAYARAN DILAKUKAN.");
							Toast.makeText(MenuUpload.this,
									"File Upload Complete.", Toast.LENGTH_SHORT)
									.show();
							// didieu

						}
					});
				}

				// close the streams //
				fileInputStream.close();
				dos.flush();
				dos.close();

				submitUploadedImage();
			} catch (MalformedURLException ex) {

				dialog.dismiss();
				ex.printStackTrace();

				runOnUiThread(new Runnable() {
					public void run() {
						messageText
								.setText("MalformedURLException Exception : check script url.");
						Toast.makeText(MenuUpload.this,
								"MalformedURLException", Toast.LENGTH_SHORT)
								.show();
					}
				});

				Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
			} catch (Exception e) {

				dialog.dismiss();
				e.printStackTrace();

				runOnUiThread(new Runnable() {
					public void run() {
						//messageText.setText("Got Exception : see logcat ");
						Toast.makeText(MenuUpload.this,
								"Got Exception : see logcat ",
								Toast.LENGTH_SHORT).show();
						
					}
				});
				Log.e("Upload file to server Exception",
						"Exception : " + e.getMessage(), e);
			}
			dialog.dismiss();
			return serverResponseCode;

		} // End else block

	}

	protected void submitUploadedImage() {
		// TODO Auto-generated method stub
		// CreateNewUploadedImage cnpd = new CreateNewUploadedImage();
		// cnpd.detailExecute();

		// new CreateUploadedImage().uploadexecute();

		String id_pemesanan = sIDPemesanan;
		String nama_file = sNama_file;//upLoadServerUri;

		// Building Parameters
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("id_pemesanan", id_pemesanan));
		params.add(new BasicNameValuePair("nama_file", nama_file));

		// getting JSON Object
		// Note that create pemesanan url accepts POST method
		JSONObject json = jsonParser.makeHttpRequest(url_uploaded_image,
				"POST", params);

		// check log cat fro response
		Log.d("Create Response", json.toString());

		// check for success tag
		try {
			int success = json.getInt(TAG_SUCCESS);

			if (success == 1) {
				/*
				 * Intent a = new Intent(getApplicationContext(),
				 * MenuPemesanan.class);
				 * a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
				 * Intent.FLAG_ACTIVITY_SINGLE_TOP); startActivity(a);
				 * 
				 * finish();
				 */
				Log.d("pemesanan", "submit pemesanan sukses");

				
			} else {
				// failed to create product
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
	
	

}
